package test.spring.boot.oauth.github.api;

import org.scribe.builder.api.DefaultApi20;
import org.scribe.model.OAuthConfig;
import org.scribe.utils.OAuthEncoder;

/**
 * @author ZCW
 * @createTime 2017/12/5
 * @lastUpdateTime 2017/12/5 ZCW
 */
public class GithubOauthApi  extends DefaultApi20 {

    /** 用户登录第三方程序授权地址 */
    private static final String AUTHORIZE_URL = "https://github.com/login/oauth/authorize?client_id=%s&redirect_uri=%s&state=%s";
    /** 授权范围 */
    private static final String SCOPED_AUTHORIZE_URL = AUTHORIZE_URL + "&scope=%s";
    /** 通过 token 获取用户信息地址 */
    private static final String ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token?state=%s";

    private final String githubState;

    public GithubOauthApi(String state){
        this.githubState = state;
    }


    @Override
    public String getAccessTokenEndpoint() {
        /* 构建接收 Token url */
        return String.format(ACCESS_TOKEN_URL, githubState);
    }

    @Override
    public String getAuthorizationUrl(OAuthConfig config) {
        /*  */
        if (config.hasScope()){
            return String.format(SCOPED_AUTHORIZE_URL, config.getApiKey(), OAuthEncoder.encode(config.getCallback()),
                    githubState, OAuthEncoder.encode(config.getScope()));
        }
        else{
            return String.format(AUTHORIZE_URL, config.getApiKey(), OAuthEncoder.encode(config.getCallback()), githubState);
        }
    }
}
